var data = fetchfacebookData('',''); //fetch initial facebook data

if (!((window.DocumentTouch && document instanceof DocumentTouch) || 'ontouchstart' in window)) {
    var script = document.createElement("script");
    script.src = "plugins/jq.desktopBrowsers.js";
    var tag = $("head").append(script);
}

var webRoot = "./";
$.ui.autoLaunch = false;
$.ui.resetScrollers=false;
var init = function () {
  window.setTimeout(function () { $.ui.launch(); }, 1500);
  $.ui.removeFooterMenu();
};
document.addEventListener("DOMContentLoaded", init, false);

$.ui.ready(function () { //jqUI is ready, panels have been setup

  //init color scheme
  if (colorScheme) { var color = colorScheme; } else { var color = 'candy'; }
  $("#jQUi > #header").addClass(color);
  $("#header li a").addClass(color);
  $("#call a").addClass(color);
  $(".contact-options a").addClass(color);
  $(".toggle").addClass(color);

  insertfacebookData(data,'init'); //insert initial facebook data
   
  var myScroller=$.ui.scrollingDivs['feed'];
  myScroller.addInfinite();
  myScroller.addPullToRefresh();

  //pull to refresh UI
  $.bind(myScroller, "refresh-trigger", function() {
    this.setRefreshContent("Release to refresh...");
  });
  var hideClose;
  $.bind(myScroller, "refresh-release", function() {
    var that = this;
    this.setRefreshContent("Loading...");
    setTimeout(function(){
      var itemID = $(".item").attr("data-id");
      data = fetchfacebookData('before',itemID); //fetch facebook data before latest post
      insertfacebookData(data,'refresh'); //prepend facebook data
    }, 1000);
    clearTimeout(hideClose);
    hideClose = setTimeout(function(){
      that.hideRefresh();
    }, 3000);
    return false;
  });
  $.bind(myScroller, "refresh-cancel", function() {
    clearTimeout(hideClose);
  });

  //bottom infinite scroll
  $.bind(myScroller,"infinite-scroll",function(){
    var itemID = $(".item:last-child").attr("data-date");
    var self=this;
    $(this.el).append("<div id='infinite'>Loading more...</div>");
    $.bind(myScroller,"infinite-scroll-end",function(){
      setTimeout(function(){
        data = fetchfacebookData('after',itemID); //fetch facebook data after latest bottom post date
        if (data) {
          insertfacebookData(data,'more');
        } else {
          $(self.el).find("#infinite").text('No more posts :(');
        }
      }, 2000);
      $.unbind(myScroller,"infinite-scroll-end");
      setTimeout(function(){
        $(self.el).find("#infinite").remove();
        self.clearInfinite();
      },3000);
    });
  });              

  myScroller.enable();

  $("#feed").css("overflow","auto");                

});

function fetchfacebookData(direction,position) {

  //direction = before OR after indicating whether to fetch posts before or after a position
  //position = either the post date or post ID to reference from

  var result = null;
  $.ajax({
    type: 'GET',
    async: false,
    url: 'https://spriii.com/inc/fetch.php?page='+facebookPageID+'&dir='+direction+'&pos='+position,
    dataType: 'json',
    cache : false,
    success: function(data){
     result = data;
    },
    error: function() {
      alert("Error loading feed :(")
    }
  });
  return result;

}

function insertfacebookData(data,type) {
  
  //init = initial app load
  //refresh = top pull-to-refresh update
  //more = infinite scroll at the bottom
  
  if (type=='init' || type=='refresh' || type=='more') {
    $.each(data.posts, function(i,post){
      if (post.photo != null) {
        photoInsert = '<img src="' + post.photo + '">';
      } else {
        photoInsert = '';
      }
      if (post.message != null) {
        messageInsert = '<div class="inner">' + post.message + '</div>';
      } else {
        messageInsert = '';
      }
      if (post.likes != null) {
        likesInsert = post.likes + ' likes | ';
      } else {
        likesInsert = '';
      }                  
      if (type=='init' || type=='more') {
        $('#feed .jqmScrollPanel').append('<div class="item" data-id="'+post.id+'" data-date="'+post.unix+'">' + messageInsert + photoInsert + '<div class="meta">' + likesInsert + post.date + '</div></div>');
      } else if (type=='refresh') {
        $('<div class="item" data-id="'+post.id+'" data-date="'+post.unix+'">' + messageInsert + photoInsert + '<div class="meta">' + likesInsert + post.date + '</div></div>').insertAfter('#feed .jqmScrollPanel > div:first-child');
      }
    });

  }

  if (type=='init') {

    //phone number
    if (hPhone) { data.phone = hPhone; }
    if (data.phone != null) {
      $('#call a').attr('href','tel:' + data.phone);
      $('#phone .ui-btn-text').text(data.phone);
      $('#phone').attr('href','tel:' + data.phone);
    } else {
      $('#call').hide();
      $('#phone').hide();
    }

    //business name
    if (hName) { data.name = hName; }
    $('#contact .name').html(data.name);    

    //address
    if (hAddress) { data.address = hAddress; }
    $('#contact .address').html(data.address);    

    //website URL
    if (hWebsite) { data.website = hWebsite; }
    if (data.website != null) {
      $('#contact .website').attr('href', data.website);
    } else {
      $('#contact .website').hide();
    }         

    //facebook link
    $('#contact .facebook').attr('href', data.link);     
    
    //description
    if (data.description != null) {
      $('#contact .description').html(data.description);
    } else {
      $('#contact .about').hide();
    }  

    //opening times
    if (data.hours != null) {
      $.each(data.hours, function(key,value){
        $('#contact .openingtimes').append('<li><span class="day">' + key + ':</span>' + value + '</li>');
      });
    } else {
      $('#contact .hours').hide();
    }              

    //insert map
    if (data.address != null) {
      $('.map').append('<iframe width="100%" height="200" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="' + data.map_src + '"></iframe>');
    }  

  }

}

/* This code is used for native apps */
var onDeviceReady = function () {
  AppMobi.device.setRotateOrientation("portrait");
  AppMobi.device.setAutoRotate(false);
  webRoot = AppMobi.webRoot + "/";


$.ui.blockPageScroll(); //block the page from scrolling at the header/footer

};

document.addEventListener("AppMobi.device.ready", onDeviceReady, false);


function hoursToggle() { //contact page opening times toggle
  $(".openingtimes").toggle();
  var openingIcon = $(".hours").find('span');
  if (openingIcon.hasClass('icon-minus')) {
    openingIcon.removeClass("icon-minus");
  } else {
    openingIcon.addClass("icon-minus");
  }
}

function aboutToggle() { //contact page description toggle
  $(".description").toggle();
  var openingIcon = $(".about").find('span');
  if (openingIcon.hasClass('icon-minus')) {
    openingIcon.removeClass("icon-minus");
  } else {
    openingIcon.addClass("icon-minus");
  }
}
